package com.wy.controller.wy;

import com.netsdk.apis.DeviceAPI;
import com.wy.model.sys.DeviceEntity;
import com.wy.model.sys.PageResult;
import com.wy.model.sys.UserEntity;
import com.wy.service.sys.UserService;
import com.wy.service.wy.DeviceService;
import com.wy.utils.BaseResponseInfo;
import com.wy.utils.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Auther: tracy
 * @Date: 2018/8/20 16:58
 * @Description: 设备管理
 */
@RestController
@RequestMapping("/devices")
@Api(value="API - ResidenceController",tags={"设备管理"})
public class DeviceController {

    private Logger log = LoggerFactory.getLogger(DeviceController.class);

    @Resource(name = "deviceServiceImpl")
    private DeviceService deviceService;

    @Resource(name = "userServiceImpl")
    private UserService userService;

    @GetMapping("")
    @ApiOperation(value="",notes="获取设备列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", required = false,dataType = "Int", defaultValue = "10"),
            @ApiImplicitParam(name = "page", value = "当前页数", required = false,dataType = "Int",defaultValue = "1"),
            @ApiImplicitParam(name = "residenceId", value = "小区ID", required = false,dataType = "Int",defaultValue = "1"),
            @ApiImplicitParam(name = "deviceName", value = "设备名称", required = false,dataType = "String",defaultValue = "")
    })
    public PageResult deviceList(Integer pageSize, Integer page,Integer residenceId,String deviceName,HttpServletRequest request) {
        List<String> rids = new ArrayList<>();
        UserEntity userEntity = userService.getUserByLoginName(request.getUserPrincipal().getName());
        if(null != userEntity) {
            String rid = userEntity.getRid();
            if(!StringUtils.isEmpty(rid)){
                List list = Arrays.asList(rid.split(","));
                rids = new ArrayList(list);
            }
        }
        PageResult pageResult = new PageResult();
        if("admin".equals(userEntity.getLoginName())){
        }else {
            rids.add("-1");//手动添加-1，如果当前登录用户无权限，则区别于admin的用户，查不到数据
        }

        pageResult.setData(deviceService.deviceList(pageSize, page * pageSize,residenceId, deviceName, rids));
        pageResult.setTotalCount(deviceService.deviceSize(pageSize, page * pageSize, residenceId,deviceName, rids));
        return pageResult;
    }

    /**
     * 新建设备
     * @param deviceEntity
     * @return
     */
    @PostMapping("/device")
    @ApiOperation(value="device",notes="新建设备")
    public BaseResponseInfo insertDevice(@RequestBody DeviceEntity deviceEntity) {
        BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
        Map<String,Object> map = new HashMap<>();
        //非空判断
        if(StringUtils.isEmpty(deviceEntity.getDeviceAddress())) {
            map.put("message","设备地址不能为空！");
            baseResponseInfo.code = 500;
            baseResponseInfo.data = map;
            return baseResponseInfo;
        }
        if(StringUtils.isEmpty(deviceEntity.getDevicePort())) {
            map.put("message","设备端口不能为空！");
            baseResponseInfo.code = 500;
            baseResponseInfo.data = map;
            return baseResponseInfo;
        }
        if(StringUtils.isEmpty(deviceEntity.getDeviceName())) {
            map.put("message","设备名称不能为空！");
            baseResponseInfo.code = 500;
            baseResponseInfo.data = map;
            return baseResponseInfo;
        }
        if(StringUtils.isEmpty(deviceEntity.getDevicePassword())) {
            map.put("message","设备密码不能为空！");
            baseResponseInfo.code = 500;
            baseResponseInfo.data = map;
            return baseResponseInfo;
        }
        if(StringUtils.isEmpty(deviceEntity.getDeviceUsername())) {
            map.put("message","设备用户名不能为空！");
            baseResponseInfo.code = 500;
            baseResponseInfo.data = map;
            return baseResponseInfo;
        }

        //非重复判断,一个通道就添加一次
        List<DeviceEntity> deviceentities = deviceService.getDeviceByAddress(deviceEntity.getResidenceId(),
                                                            deviceEntity.getDeviceAddress(),
                                                            deviceEntity.getDeviceChannelId());
        if(null != deviceentities && deviceentities.size() > 0) {
            map.put("message","设备通道已存在！");
            baseResponseInfo.code = 500;
            baseResponseInfo.data = map;
            return baseResponseInfo;
        }

        deviceentities = deviceService.getDeviceByName(deviceEntity.getResidenceId(),deviceEntity.getDeviceName());
        if(null != deviceentities && deviceentities.size() > 0) {
            map.put("message","设备名称已存在！");
            baseResponseInfo.code = 500;
            baseResponseInfo.data = map;
            return baseResponseInfo;
        }

        deviceService.insertDevice(deviceEntity);
        log.debug("The method is ending");
        return baseResponseInfo;
    }

    /**
     * 修改设备信息
     * @param deviceEntity
     * @param id
     * @return
     */
    @PutMapping("/{id}")
    public BaseResponseInfo updateDevice(@RequestBody DeviceEntity deviceEntity, @PathVariable int id) {
        BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
        Map<String,Object> map = new HashMap<>();
        //todo 校验处理
        deviceService.updateDevice(deviceEntity);
        log.debug("The method is ending");
        return baseResponseInfo;
    }

    /**
     * 删除设备信息
     *
     * @param groupId
     * @return
     */
    @DeleteMapping("")
    public void deleteDevices(@RequestBody List<String> groupId) {
        deviceService.deleteDevices(groupId);
    }

    /**
     * 根据小区id获取门禁设备
     * @param rid
     * @return
     */
    @GetMapping("/getDeviceByRid")
    public BaseResponseInfo getDeviceByRid(Integer rid) {
        BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
        List<DeviceEntity> deviceEntities = deviceService.getDeviceByRidAndType(rid,4);
        baseResponseInfo.data = deviceEntities;
        return baseResponseInfo;
    }

    /**
     * 指定设备id开门
     */
    @GetMapping("/openDoor/{id}")
    public BaseResponseInfo openDoor(@PathVariable int id){
        BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
        baseResponseInfo.data = deviceService.openDoor(id);
        return baseResponseInfo;
    }


    @GetMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response,Integer residenceId, String deviceName) throws Exception {
//        response.setHeader("content-Type", "application/vnd.ms-excel");
//        response.setHeader("Content-Disposition", "attachment;filename="+new String( "设备信息.xls".getBytes("gb2312"), "ISO8859-1" ));
//        List<String> rids = new ArrayList<>();
//        UserEntity userEntity = userService.getUserByLoginName(username);
//        if(null != userEntity) {
//            String rid = userEntity.getRid();
//            if(!StringUtils.isEmpty(rid)){
//                rids = Arrays.asList(rid.split(","));
//            }
//        }
//        List<Residence> list = new ArrayList<>();
//        if("admin".equals(username)) {
//            list = deviceService.deviceList(null, null,residenceId,deviceName);
//        }else {
//            rids.add("-1");//手动添加-1，如果当前登录用户无权限，则区别于admin的用户，查不到数据
//            list = residenceService.residenceList1(null, null, projectName, rids);
//        }
//        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), Residence.class, list);
//        workbook.write(response.getOutputStream());
    }

    /**
     * 数据导入
     * @param file
     */
    @PostMapping("/import")
    public Map<String,String> importExcel(MultipartFile file){
        Map<String,String> map = FileUtil.judgeRepeatExcel(file,2,1);
//        if(map.isEmpty()) {
//            List<Residence> residenceList = FileUtil.importExcel(file, 0, 1, Residence.class);
//
//            if (residenceList != null) {
//                System.out.println("导入数据一共【" + residenceList.size() + "】行");
//               List<Residence> temp = residenceService.selectByName(residenceList);
//               if(temp.size() == 0){
//                   residenceService.insertBatch(residenceList);
//               }else{
//                   for(Residence residence : temp){
//                       map.put(String.valueOf(residence.getId()),residence.getProjectName());
//                   }
//
//               }
//
//            }
//        }
        return  map;
    }

}
